import React, {Component} from 'react'
import {Popover, Button, Icon} from 'antd'
import {emoji} from '../../common/js/emoji'
import propTypes from 'prop-types'

function selectText(dom, text = '', emo) {
  let start, end
  start = end = text.length
  if (dom && dom.selectionStart && dom.selectionEnd) {
    start = dom.selectionStart
    end = dom.selectionEnd
  }
  return text.substr(0, start) + emo.alt + text.substr(end)
}

class Emoji extends Component {

  state = {
    visible: false
  }

  handleVisibleChange = (visible) => {
    this.setState({visible})
  }

  onSelect = (item) => {
    this.props.onSelect(item)
    this.handleVisibleChange(false)
  }

  render() {
    const {placement, style} = this.props

    return (
      <Popover title={`选择表情`} placement={placement} onVisibleChange={this.handleVisibleChange} trigger="click" visible={this.state.visible} content={
        <div
          style={{
            height: 200,
            width: 400,
            overflowY: 'auto'
          }}
        >
          {
            emoji.map((item, key) => (
              <img
                title={item.alt}
                style={{
                  margin: 3,
                  width: 32,
                  cursor: 'pointer'
                }}
                src={item.src}
                alt={item.key}
                key={key}
                onClick={e => this.onSelect(item)}
              />
            ))
          }
        </div>
      } >
        <Button
          type="link"
          title="表情"
        >
          <Icon style={{
            fontSize: 20,
            color: '#fff',
            ...style
          }} type="smile" />
        </Button>
      </Popover>
    )
  }
}

Emoji.propTypes = {
  placement: propTypes.string,
  onSelect: propTypes.func,
  style: propTypes.object
}

Emoji.defaultProps = {
  placement: 'top',
  onSelect: () => {},
  style: {}
}

export {Emoji, selectText}
